package com.cjq.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cjq.domain.User;
import com.cjq.service.UserService;
import com.cjq.utils.Constant;
import com.cjq.utils.JwtUtils;
import com.cjq.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.*;

/**
 * @author junqiancai@foxmail.com
 * @since 2021/6/9 15:53
 */
@RestController
public class OauthController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/login/dgut")
    public Result test(HttpServletRequest request){
        final String token = request.getParameter("token");
        if(!StringUtils.hasText(token)){
            Result.fail(401,"回调请求无token，或token无效");
        }
        RestTemplate template = new RestTemplate();
        String getUserInfoURL = "https://cas.dgut.edu.cn/oauth/getUserInfo";
        String verifyUrl = "https://cas.dgut.edu.cn/ssoapi/v2/checkToken";
        JacksonJsonParser parser = new JacksonJsonParser();
        //准备参数
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("appid","javaee");
        map.put("appsecret","b3b52e43ccfd");
        //发请求获取access_token
        Map<String, Object> resMap = parser.parseMap(template.postForObject(verifyUrl,map,String.class));
        if(resMap==null || resMap.get("error").equals("1")){
            return Result.fail(Result.NOT_AUTH,"token不存在或已过期",null);
        }
        //登录成功，根据access_token获取用户信息
        map.clear();
        map.put("access_token",resMap.get("access_token"));
        map.put("openid",resMap.get("openid"));
        resMap = parser.parseMap(template.postForObject(getUserInfoURL,map,String.class));
        //判断是否需要新增用户记录
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, resMap.get("username")));
        if(user!=null){
            //数据库中已有记录，返回jwt
            String jwt = generateJwtToken(user);
            redisTemplate.opsForValue().set(JwtUtils.REDIS_PREFIXED+jwt,"", Duration.ofSeconds(JwtUtils.EXPIRE_TIME));
            return Result.succeed(Result.SUCCESS,"登录成功",jwt);
        }
        //数据库中没有记录，新增用户信息，返回jwt
        user = new User();
        final String group = (String) resMap.get("group");
        int userType = 1;
        if(!"Student".equals(group))userType=0; //不是学生用户就把userType设置为0
        user.setUsername((String) resMap.get("username"))
                .setRealName((String) resMap.get("name"))
                .setUserType(userType)
                .setDepartment((String) resMap.get("faculty_title"))
                .setRoleId(2)
                .setEnablePassword(0)
                .setSchool("DGUT");
        userService.save(user);
        String jwt = generateJwtToken(user);
        redisTemplate.opsForValue().set(JwtUtils.REDIS_PREFIXED+jwt,"", Duration.ofSeconds(JwtUtils.EXPIRE_TIME));
        return Result.succeed(Result.SUCCESS,"初次登录",generateJwtToken(user));
    }
    private String generateJwtToken(User user){
        HashMap<String, Object> map = new HashMap<>();
        //利用user中的信息,用于生成jwtToken
        map.put("id",user.getId());
        map.put("username",user.getUsername());
        map.put("userType",user.getUserType());
        map.put("realName",user.getRealName());
        map.put("role", user.getRoleId());
        return JwtUtils.createJwtToken(map);
    }
}
